package models

import (
	"LazyPig/database"
	"errors"
	"fmt"
	"github.com/robfig/cron/v3"
	"strconv"
	"strings"
	"time"
)

type Row struct {
	RuleId	int	`form:"ruleId" binding:"required"`
	Type	int	`form:"type" binding:"required"`
}

func Attendance(r *Row, uid float64) error {
	data := make(map[string]interface{})
	data["ruleId"] = r.RuleId
	data["type"] = r.Type
	data["userId"] = uid
	_, err := database.SqlDB.Insert("attendance", data)
	if err != nil {
		return errors.New("打卡失败")
	}
	return nil
}

func GetAbList(id float64) (interface{}, error)  {
	rows, err := database.SqlDB.GetAll("SELECT * FROM absenteeism WHERE userId = ?", id)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	return rows, nil
}

func GetAtList (id float64) (interface{}, error)  {
	rows, err := database.SqlDB.GetAll("SELECT * FROM attendance WHERE userId = ?", id)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	return rows, nil
}

/*
	缺勤逻辑 每天晚上11点查询所有用户是否完成考勤组打卡，如未打卡则记录到缺勤表
*/
func absenteeism()  {
	fmt.Println("定时任务开始")
	// 查询所有有考勤组的用户
	rows, err := database.SqlDB.GetAll("SELECT u.id, r.id AS ruleId, r.period, r.time FROM user AS u LEFT JOIN rule AS r ON r.id = u.rule")
	if err != nil {
		fmt.Println(err)
	}
	// 遍历所有用户
	t := time.Now()
	toDay := time.Now().Format("2006-01-02")
	for _, item := range rows {
		// 判断该用户今天是否该打卡 是则检查是否打过卡(该考勤组)
		period := item["period"]
		if period != nil {
			psth, ok := period.(string)
			if !ok {
				psth = strconv.Itoa(period.(int))
			}
			if strings.Index(psth, strconv.Itoa(int(t.Weekday()))) != -1 {
				jilu, _ := database.SqlDB.GetAll("SELECT * FROM attendance WHERE create_time > ? AND userId = ? AND ruleId = ?", toDay, item["id"], item["ruleId"])
				fmt.Println(len(jilu))
				if len(jilu) <= 0 {
					data := make(map[string]interface{})
					data["userId"] = item["id"]
					data["ruleId"] = item["ruleId"]
					_, _ = database.SqlDB.Insert("absenteeism", data)
				}
			}
		}
	}
}

func timer()  {
	c := cron.New(cron.WithSeconds())
	spec := "0 0 23 * * ?"
	c.AddFunc(spec, func() {
		absenteeism()
	})
	c.Start()
	defer c.Stop()
	select{}
}

func init() {
	go timer()
}

